import React from 'react';
import {getStore} from "./StoreConfiguration"
import {hasValue} from "../util/TextCheck/TextCheck"
import {doDisplayWarnMessage} from "../component/Message/Action"
import User from "../model/User/User"


export const FetchStatus = {
  NoFetch: 'noFetch',
  Start: 'start',
  Success: 'success',
  Failed: 'failed',
};

export const RequestMethod = {
  Get: 'Get',
  Post: 'Post',
};

export const Request = (path: String, method: String, params) => new Promise((resolve, reject) => {

  // path = Path(path);

  let Authorization = null;
  let token = getStore().getState().onToken;
  if (hasValue(token)) {
    // Authorization = {'Authorization': 'Bearer ' + token}
    Authorization = {'Authorization': token}
  }

  let param = {
    ...params,
    token: token
  }

  let requestInit = {
    method: method,
    headers: {'Content-Type': 'application/json', ...Authorization},
  };

  if (requestInit.method === RequestMethod.Get) {
    let esc = encodeURIComponent;
    let query = Object.keys(param)
    .filter(k => (param[k] !== null && param[k] !== ''))
    .map(k => esc(k) + '=' + esc(param[k]))
    //               .map(k => (param[k] !== null ? esc(k) + '=' + esc(param[k]):''))

    .join('&');
    path = path + '?' + query;
  } else {
    requestInit.body = JSON.stringify(param);
  }


  return fetch(path, requestInit)
  .then(response => {
    console.log('----------------------Start----------------------');
    console.log(path);
    console.log(JSON.stringify(param));
    console.log(response);
    console.log('=======================End=======================');
    return statusFilter(response)
  })
  .then(response => {

    if (response._bodyText === '') {
      response._bodyText = '{}'
    }
    return response.json()
  })
  .then(json => codeFilter(json))
  .then(json => {

    resolve(json);
  })
  .catch((error) => {
    let message;
    if (error.message === 'Network request failed') {
      message = '网络不稳定或者网络异常，别紧张，请确认网络正常后再试';
    } else {
      message = error.message;
    }
    reject(Error(message || '服务器异常,请稍后再试'));
  });
});

export const RequestAction = (path: String, method: String, param, action) => dispatch => {

    dispatch(fetchActionCreator(action, FetchStatus.Start));
    Request(path, method, param)
        .then(json => dispatch(fetchActionCreator(action, FetchStatus.Success, json)))
        .catch(error => {
            dispatch(doDisplayWarnMessage(error.message));
            dispatch(fetchActionCreator(action, FetchStatus.Failed, error));
        })

    /*dispatch(fetchActionCreator(action, FetchStatus.Start));

    //检测网络连接信息
    NetInfo.fetch().done((connectionInfo) => {
        if(connectionInfo === "WIFI"){
            path=global.AppRequestPath.split('/huasheng')[0]+'/huasheng'+path.split('/huasheng')[1]
        }else{
            path=global.AppRequestPath_spare.split('/huasheng')[0]+'/huasheng'+path.split('/huasheng')[1]
        }

        NetInfo.isConnected.fetch().done((isConnected) => {
            if(isConnected === false &&  ){
                path=global.AppRequestPath_spare.split('/huasheng')[0]+'/huasheng'+path.split('/huasheng')[1]
            }else{
                path=
            }

            console.log("========================================================="+isConnected)
            console.log("========================================================="+connectionInfo)
            console.log("========================================================="+path)

            Request(path, method, param)
                .then(json => dispatch(fetchActionCreator(action, FetchStatus.Success, json)))
                .catch(error => {
                    dispatch(doDisplayWarnMessage(error.message));
                    dispatch(fetchActionCreator(action, FetchStatus.Failed, error));
                })


        });


    });*/
};

export const statusFilter = (response) => new Promise(function (resolve, reject) {
  // console.log('statusFilter ErrorCode');
  // console.log('Code:' + response.status);
  // console.log('message:' + response.message);

  switch (response.status) {

    case 500: {
      reject(new Error(response.message || '服务器异常,请稍后再试'));
      break;
    }
    case 400: {
      reject(new Error(response.message || '服务器异常,请稍后再试'));
      break;
    }
    case 401: {
      // reject(new Error(response.message || '登录超时,请重新登录'));
      reject(new Error(response.message || '连接服务器超时,请稍后重试'));
      break;
    }
    case 404: {
      reject(new Error(response.message || '服务器异常,请稍后再试'));
      break;
    }
    case 202: {
      resolve(response);
      // reject(new Error(response.message || '服务器异常,请稍后再试'));
      break;
    }
    case 200: {
      resolve(response);
      break;
    }
    default: {
      reject(new Error(response.message || '服务器异常,请稍后再试'));
      break;
    }
  }
});


export const codeFilter = (json) => new Promise(function (resolve, reject) {
  console.log('codeFilter ErrorCode');
  console.log('Code:' + json.code);
  console.log('message:' + json.message);

  if (json.code) {
    reject(new Error(json.message || '服务器异常,请稍后再试'))
  } else {
    resolve(json)
  }
});

export const fetchActionCreator = (action, status, json, error,) => {
  switch (status) {
    case FetchStatus.Start: {
      action.status = FetchStatus.Start;
      action.json = json;
      return action;
    }
    case  FetchStatus.Success: {
      action.status = FetchStatus.Success;
      action.json = json;
      return action;
    }
    case  FetchStatus.Failed: {
      action.status = FetchStatus.Failed;
      action.json = json;
      action.error = error;
      return action;
    }
  }
};


